package com.fourth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fourth.dao.PermissionDao;
import com.fourth.service.PermissionService;
import com.ljx.entity.Permission;
import com.ljx.security.util.WebUtils;
import com.ljx.utils.JwtUtil;
import com.ljx.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author LJX
 * @Description: TODO
 * @Date: 2023/2/23 10:06
 * @Version 1.0
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionDao, Permission> implements PermissionService {
	@Autowired
	private PermissionDao permissionDao;
	@Override
	public List<Permission> selectPermissionByEmpId(String empid) {
		return permissionDao.selectPermissionByEmpId(empid);
	}

	@Override
	public Result leftMenus() {
		String token = WebUtils.getRequest().getHeader("token");
		Map<String, Object> map = JwtUtil.getTokenChaim(token);
		Object username = map.get("username");
		//根据用户名查询该用户具有的菜单。
		List<Permission> permissions = permissionDao.findPermissionByUsername(username);
		List<Permission> firsts = firsts(permissions);

		return new Result(2000,"查询左侧菜单成功",firsts);
	}



	private List<Permission> firsts(List<Permission> permissions){
		//1.一级菜单
		List<Permission> firsts=new ArrayList<>();
		for (Permission permission:permissions){
			if(permission.getPid().equals("0")){
				firsts.add(permission);
			}
		}

		//2.查询一级菜单下的二级菜单
		for(Permission first:firsts){
			List<Permission> children=new ArrayList<>();
			for(Permission p:permissions){
				if(first.getId().equals(p.getPid())){
					children.add(p);
				}
			}
			first.setChildren(children);
		}
		return firsts;
	}
}
